﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using log4net.Appender;

namespace WpfBeyond
{
    class LogHelp
    {
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
        private static object thisLock = new object();
        public static void Info(string info)
        {
            lock (thisLock)
            {
                if (loginfo.IsInfoEnabled)
                {
                    loginfo.Info(info);
                }
            }
        }

        public static void Error(string info)
        {
            lock (thisLock)
            {
                if (logerror.IsErrorEnabled)
                {
                    logerror.Error(info);
                }
            }
        }

        /// <summary>
        /// 日志保留多少天
        /// </summary>
        /// <param name="logFilePath"></param>
        /// <param name="saveDays"></param>
        public static void ClearLog(int saveDays)
        {
            lock (thisLock)
            {                
                Task.Run(() => {
                    var apps = loginfo.Logger.Repository.GetAppenders();
                    if (apps.Length <= 0)
                    {
                        return;
                    }
                    var now = DateTime.UtcNow.AddDays(-10);
                    foreach (var item in apps)
                    {
                        if (item is RollingFileAppender)
                        {
                            RollingFileAppender roll = item as RollingFileAppender;
                            var dir = Path.GetDirectoryName(roll.File);
                            var files = Directory.GetFiles(dir, "*.*");                            

                            foreach (var filePath in files)
                            {
                                var file = new FileInfo(filePath);
                                if (file.CreationTimeUtc < now)
                                {
                                    try
                                    {
                                        file.Delete();
                                    }
                                    catch (Exception)
                                    {

                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    }
}
